
package facade;

import remoteEntity.Role;
import remoteEntity.User;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import util.HashUtil;

/**
 * Interacts with the user table.
 * This version uses native mysql queries.
 * @author vho
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {
    @PersistenceContext(unitName = "filecityeePU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }
    
    public void setRole(User user, Role role) {
        String query = "update user set role="+role.getId()+" where id="+user.getId()+";";
        em.createNativeQuery(query).executeUpdate();
    }
    
    /**
     * Attempt to log in the given user, returns null if username or password was incorrect.
     * @param user
     * @return 
     */
    public User login(User user) {
        System.out.println("Facade attempting login");
        String hash = HashUtil.getSHA1(user.getPassword(), true);
        user.setPassword(hash);
        User foundUser;
        try {
            foundUser = (User) em.createNativeQuery("select * from user where username='"+user.getUsername()+"';",User.class).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        //Secure compare to avoid sidechannel attacks
        int diff = 0;
        for(int i=0; i<foundUser.getPassword().length(); ++i) {
            diff += foundUser.getPassword().charAt(i) ^ hash.charAt(i);
        }
        if(diff!=0)
            return null;
        else
            return foundUser;
    }
    
    /**
     * insert a new user into the database.
     * @param user
     * @throws Exception 
     */
    public void register(User user) throws Exception {
        //Regular user
        Role role = em.find(Role.class, 2);
        String hash = HashUtil.getSHA1(user.getPassword(), true);
        
        String query ="INSERT INTO user VALUES (null,'"+user.getUsername()+"','"+hash+"','"+user.getEmail()+"',"+role.getId()+",'"+user.getFirstname()+"','"+user.getLastname()+"');";
        em.createNativeQuery(query).executeUpdate();
    }
}
